// src/lib/getBlogPosts.ts
import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
import { markdownToHtml } from './markdown';

export interface BlogPostProps {
  slug: string;
  title: string;
  content: string;
  htmlContent: string;
}

export async function getBlogPosts(): Promise<BlogPostProps[]> {
  try {
    const filesDirectory = path.join(process.cwd(), '/src/assets/md');
    let fileNames = fs.readdirSync(filesDirectory);

    // 只需要md格式的文件
    fileNames = fileNames.filter(fileName => fileName.endsWith('.md'));

    const allFilesData = await Promise.all(fileNames.map(async (fileName) => {
      const fullPath = path.join(filesDirectory, fileName);
      const fileContents = fs.readFileSync(fullPath, 'utf8');
      // 头部原数据加md内容
      const { data, content: markdown } = matter(fileContents);
      const htmlContent = await markdownToHtml(markdown);

      return {
        slug: fileName.replace('.md', ''),
        title: fileName,
        content: markdown,
        htmlContent,
      };
    }));

    return allFilesData;

  } catch (error) {
    console.error('Error in getBlogPosts:', error);
    throw error;
  }
}